package com.winsdom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.winsdom.dto.JurisdictionDTO;
import com.winsdom.entity.Category;
import com.winsdom.entity.SysUser;
import com.winsdom.entity.UserProjects;
import com.winsdom.exception.BaseException;
import com.winsdom.mapper.CategoryMapper;
import com.winsdom.mapper.SysUserMapper;
import com.winsdom.mapper.UserProjectsMapper;
import com.winsdom.service.IUserProjectsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户管辖项目表 服务实现类
 * </p>
 *
 * @author
 * @since 2025-05-12
 */
@Service
@AllArgsConstructor
public class UserProjectsServiceImpl extends ServiceImpl<UserProjectsMapper, UserProjects> implements IUserProjectsService {

    private final SysUserMapper userMapper;
    private final CategoryMapper categoryMapper;
    private final UserProjectsMapper userProjectsMapper;

    /**
     * 提交管辖项目
     * @param jurisdictionDTO 用户管辖信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserProjects(JurisdictionDTO jurisdictionDTO) {
        // 1. 根据用户名查询用户ID
        SysUser user = userMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, jurisdictionDTO.getUsername()));

        if (user == null) {
            throw new BaseException("用户不存在");
        }

        if (user.getStatus() == 0) {
            throw new BaseException("账号已禁用，不能管辖项目");
        }

        if (!jurisdictionDTO.getNodeIds().isEmpty()) {
            // 2. 验证所有节点是否为楼盘（type=3）
            Integer count = categoryMapper.selectCount(new LambdaQueryWrapper<Category>()
                    .in(Category::getId, jurisdictionDTO.getNodeIds())
                    .ne(Category::getType, 3));

            if (count > 0) {
                throw new BaseException("包含非楼盘类型节点");
            }
        }

        // 3. 查询用户当前已关联的项目ID
        List<Long> existingNodeIds = userProjectsMapper.selectList(
                        new LambdaQueryWrapper<UserProjects>()
                                .eq(UserProjects::getUserId, user.getId())
                ).stream()
                .map(UserProjects::getCategoryId)
                .collect(Collectors.toList());

        // 4. 计算需要删除和新增的数据
        List<Long> idsToDelete = existingNodeIds.stream()
                .filter(id -> !jurisdictionDTO.getNodeIds().contains(id))
                .collect(Collectors.toList());

        List<UserProjects> projectsToInsert = jurisdictionDTO.getNodeIds().stream()
                .filter(id -> !existingNodeIds.contains(id))
                .map(id -> new UserProjects()
                        .setCategoryId(id)
                        .setUserId(user.getId()))
                .collect(Collectors.toList());

        // 5. 执行删除和插入（仅在必要时操作）
        if (!idsToDelete.isEmpty()) {
            userProjectsMapper.delete(new LambdaQueryWrapper<UserProjects>()
                    .eq(UserProjects::getUserId, user.getId())
                    .in(UserProjects::getCategoryId, idsToDelete));
        }

        if (!projectsToInsert.isEmpty()) {
            boolean result = this.saveBatch(projectsToInsert);
            if (!result) {
                throw new BaseException("批量插入失败");
            }
        }
    }
}
